//
//  NetManager.m
//  Sports
//
//  Created by up72_01 on 15/8/27.
//  Copyright (c) 2015年 wisdom. All rights reserved.
//

#import "NetManager.h"
#import "AppDelegate.h"
#import "AESHelp.h"
#import "MTool.h"
@implementation NetManager

@synthesize delegate;

@synthesize requestId;
@synthesize loadingText;
@synthesize isRequesting;
@synthesize isShowLoading;
@synthesize requestDic;


- (id)init
{
    self = [super init];
    if (self) {
        loadingText  = @"";
        isShowLoading = NO;
        isRequesting = NO;
    }
    return self;
}



//加密上传
- (void)sendPOSTRequestToServerWithURL:(NSString *)urlString postData:(NSMutableDictionary*)messageDic
{
    [self addLoadingView];
    
    NSString *string = HTTP_HOST;
    
    string = [string stringByAppendingString:urlString];
    
    if (delegate) {
        if ([delegate respondsToSelector:@selector(requestStart:)]) {
            [delegate requestStart:self];
        }
    }
    
    
    //转换为jsonString
    NSString *jsonString = [MTool DataTOjsonString:messageDic];
    
    //加密jsonString
    NSString *encrypt = [AESHelp encryptMothed2:jsonString];
    NSMutableDictionary *encryptDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:encrypt,@"value", nil];
    
    //声明上传数据是json类型
    AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
    serializer.timeoutInterval = 10.f;
    NSError *requestError;
    NSMutableURLRequest *request = [serializer requestWithMethod:@"POST" URLString:string parameters:encryptDic error:&requestError];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (delegate) {
            if ([delegate respondsToSelector:@selector(requestDidFinished:result:)]) {
                //解密数据
//                NSString *jsonString = [AESHelp decryptMothed2:[responseObject objectForKey:@"value"]];
//                NSMutableDictionary *mutDic = [MTool jsonStringToDictionary:jsonString];
                NSMutableDictionary *mutDic = responseObject;
                [delegate requestDidFinished:self result:mutDic];
            }
        }
        [self removeLoadingView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (delegate) {
            if ([delegate respondsToSelector:@selector(requestError:error:)]) {
                [delegate requestError:self error:error];
            }
        }
        [self removeLoadingView];
    }];
    [operation start];
    
}

//上传文件
- (void)uploadWithUrl:(NSString *)url body:(NSDictionary *)body method:(NSString *)method constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))bodyBlock
{
    [self addLoadingView];
    
    NSString *string = HTTP_HOST;
    
    string = [string stringByAppendingString:url];
    
    if (delegate) {
        if ([delegate respondsToSelector:@selector(requestStart:)]) {
            [delegate requestStart:self];
        }
    }
    
    //加密
    //转换为jsonString
    NSString *jsonString = [MTool DataTOjsonString:body];
    
    //加密jsonString
    NSString *encrypt = [AESHelp encryptMothed2:jsonString];
    NSMutableDictionary *encryptDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:encrypt,@"value", nil];
    
    AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializerWithWritingOptions:0];
    serializer.timeoutInterval = 15.f;
    
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:method URLString:string parameters:encryptDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        bodyBlock(formData);
    } error:nil];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (delegate) {
            if ([delegate respondsToSelector:@selector(requestDidFinished:result:)]) {
                
                //解密
//                NSString *jsonString = [AESHelp decryptMothed2:[responseObject objectForKey:@"value"]];
//                NSMutableDictionary *mutDic = [MTool jsonStringToDictionary:jsonString];
                NSMutableDictionary *mutDic = responseObject;
                [delegate requestDidFinished:self result:mutDic];
            }
        }
        [self removeLoadingView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (delegate) {
            if ([delegate respondsToSelector:@selector(requestError:error:)]) {
                [delegate requestError:self error:error];
            }
        }
        [self removeLoadingView];
    }];
    [operation start];
}


//上传加密的
- (void)sendPOSTRequestToServerWithURL:(NSString *)urlString postData:(NSMutableDictionary *)messageDic deCode:(NSString *)deCode
{
    
    [self addLoadingView];
    
    NSString *string = HTTP_HOST;
    
    string = [string stringByAppendingString:urlString];
    
    if (delegate) {
        if ([delegate respondsToSelector:@selector(requestStart:)]) {
            [delegate requestStart:self];
        }
    }
    
    AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializerWithWritingOptions:0];
    serializer.timeoutInterval = 10.f;
    NSError *requestError;
    NSMutableURLRequest *request = [serializer requestWithMethod:@"POST" URLString:string parameters:messageDic error:&requestError];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    [manager.requestSerializer setValue:deCode forHTTPHeaderField:@"encryptValue"];

    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (delegate) {
            if ([delegate respondsToSelector:@selector(requestDidFinished:result:)]) {
                [delegate requestDidFinished:self result:responseObject];
            }
        }
         [self removeLoadingView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (delegate) {
            if ([delegate respondsToSelector:@selector(requestError:error:)]) {
                [delegate requestError:self error:error];
            }
        }
        [self removeLoadingView];
    }];
    [operation start];
}



- (void)addLoadingView
{
    
    isRequesting = YES;
    
    if (loadingText)
    {
        isShowLoading = YES;
        
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        
        LoadingView *view = [[LoadingView alloc] initWithFrame:appDelegate.window.bounds withText:loadingText];
        view.userInteractionEnabled = YES;
        view.tag = 123456;
        [appDelegate.window addSubview:view];
    }
}

- (void)removeLoadingView
{
    isRequesting = NO;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    LoadingView *view = (LoadingView *)[keyWindow viewWithTag:123456];
    [view removeFromSuperview];
    
    loadingText = nil;
}



@end
